<?php
namespace app\index\taglib;

use think\template\TagLib;

class Scms extends TagLib {
    protected $tags   =  [
        'list'      => ['attr' => 'name,table,field,where,order,limit,pagename'],
    ];
   
    public function tagList($tag, $content)
    {
        $tag['name'] = empty($tag['name']) ? 'v' : $tag['name'];

        if (empty($tag['table'])) {
            return $content;
        }

        $tag['field'] = empty($tag['field']) ? '*' : $tag['field'];
        $tag['where'] = empty($tag['where']) ? '' : $tag['where'];
        $tag['order'] = empty($tag['order']) ? '' : $tag['order'];
        $tag['limit'] = empty($tag['limit']) ? 0 : intval($tag['limit']);

        $parse  = '';

        if ($tag['limit'] && !empty($tag['pagename'])) {
            $parse .= '<?php $list_' . $tag['name'] . ' = Db::table("' . $tag['table'] . '")->field("' . $tag['field'] . '")->where("' . $tag['where'] . '")->order("' . $tag['order'] . '")->paginate(' . $tag['limit'] . '); ?>';
            $parse .= '{foreach $list_' . $tag['name'] . ' as $' . $tag['name'] . '_k => $' . $tag['name'] . '}';
            $parse .= $content;
            $parse .= '{/foreach}';
            $parse .= '<?php $' . $tag['pagename'] . ' = $list_' . $tag['name'] . '->render(); ?>';
        } else {
            $parse .= '{foreach :Db::table("' . $tag['table'] . '")->field("' . $tag['field'] . '")->where("' . $tag['where'] . '")->order("' . $tag['order'] . '")->limit(' . $tag['limit'] . ')->select() as $' . $tag['name'] . '_k => $' . $tag['name'] . '}';
            $parse .= $content;
            $parse .= '{/foreach}';
        }

        return $parse;
    }
}